<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-包装入库申请`"
		width="1400px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:show-confirm-btn="pageType !== 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail' || ruleForm.auditState === 1" label-width="110px" :show-message="false">
			<div ref="box1">
				<div class="flex-start-center margin-bottom-4" style="font-size: 13px;">
					<el-tag v-if="!ruleForm.code" type="primary" effect="plain" class="">
						<span class="el-icon-tickets item-gap"></span>
						<span>基本信息</span>
					</el-tag>
					<div v-else style="font-size: 16px;">
						<span class="el-icon-star-off item-gap"></span>
						<span>{{ ruleForm.code || '系统自动生成' }}</span>
					</div>
				</div>
				<jk-card>
					<el-row class="flex-start-center-wrap">
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="生产日期" prop="belongDate">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.belongDate }}</span>
								<jk-date-picker v-else v-model="ruleForm.belongDate" size="medium" placeholder="生产日期" @change="getOrderInfoRequest" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="仓库">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.warehouseName }}</span>
								<el-select v-else v-model="ruleForm.warehouseName" :disabled="dataId ? true :false" class="width-100-percent" size="medium" placeholder="仓库" @change="onWarehouseChange">
									<el-option
										v-for="item in warehouseList"
										:key="item.id"
										:label="item.name"
										:value="item.id"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item class="margin-bottom-0" label="备注">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.remark }}</span>
								<el-input v-else v-model="ruleForm.remark" :rows="1" type="textarea" placeholder="请输入..." />
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
				<div class="margin-top-10 margin-bottom-4 flex-between-center">
					<el-tag class="margin-bottom-4 el-icon-tickets margin-top-10" effect="plain">入库单明细</el-tag>
					<el-row>
						<el-col :span="8">
							<div style="display: flex; align-items: center;justify-content: center; width: 100px">
								<div style="width: 20px; height: 20px; border-radius: 50px; background-color: #ff4949"></div><div style="padding: 0 0 0 5px">生产订单</div>
							</div>
						</el-col>
						<el-col :span="8">
							<div style="display: flex; align-items: center;justify-content: center; width: 100px">
								<div style="width: 20px; height: 20px; border-radius: 50px; background-color: #ff9900"></div><div style="padding: 0 0 0 5px">改包装知单</div>
							</div>
						</el-col>
						<el-col :span="8">
							<div style="display: flex; align-items: center;justify-content: center; width: 100px">
								<div style="width: 20px; height: 20px; border-radius: 50px; background-color: #42d885"></div><div style="padding: 0 0 0 5px">包装返工单</div>
							</div>
						</el-col>
					</el-row>
					<div class="flex-start-center"></div>
				</div>
			</div>
			<jk-table
				border
				show-footer
				:footer-method="footerMethod"
				:data="ruleForm.packageInStorageItemList"
				:height="dialogTableHeight - 20"
			>
				<vxe-column :visible="pageType !== 'detail' && ruleForm.auditState !== 1" title="操作" align="center" field="operation" :width="70">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button size="mini" icon="el-icon-minus" @click="ruleForm.packageInStorageItemList.splice(scope.rowIndex, 1)" />
						</div>
					</template>
				</vxe-column>
				<vxe-column title="品种" align="left" field="productName" width="150">
					<template slot-scope="scope">
						<div style="display: flex">
							<repair-state-bar :status="scope.row.type"></repair-state-bar>
							<span>{{ scope.row.productName }}</span>
						</div>
					</template>
				</vxe-column>
				<vxe-column title="批号" align="left" field="batchCode" :min-width="120"></vxe-column>
				<vxe-column title="纸管颜色" align="left" field="unitPrice" :min-width="80">
					<template slot-scope="scope">
						<span>{{ scope.row.matePaperColor || paperTubeList(scope.row.paperTubeList) }}</span>
					</template>
				</vxe-column>
				<vxe-column title="腰绳颜色" align="left" field="waistPopeList" :min-width="80">
					<template slot-scope="scope">
						<span>{{ scope.row.mateWaistColor || waistPopeList(scope.row.waistPopeList) }}</span>
					</template>
				</vxe-column>
				<vxe-column title="标签颜色" align="left" field="unitPrice" :min-width="80">
					<template slot-scope="scope">
						<span>{{ scope.row.mateLabelColor || labelColorList(scope.row.labelColorList) }}</span>
					</template>
				</vxe-column>
				<vxe-column title="申请入库包数" align="right" field="applyInNum" :width="100"></vxe-column>
				<vxe-column title="申请入库重量" align="right" field="applyInQty" :width="100"></vxe-column>
				<vxe-column title="活码数" align="right" field="packLiveCode" :width="70"></vxe-column>
				<vxe-column title="活码重量" align="right" field="packLiveCodeQty" :width="70"></vxe-column>
				<vxe-column title="总件数" align="right" field="inPackageQty" :width="70"></vxe-column>
				<vxe-column title="入库总重量" align="right" field="inQty" :width="80"></vxe-column>
				<vxe-column title="货位" align="left" field="positionId" :min-width="800">
					<template slot="header">
						<el-row :gutter="24">
							<el-col :span="6">货位</el-col>
							<el-col :span="3">申请入库包数</el-col>
							<el-col :span="3">申请入库重量</el-col>
							<el-col :span="3">活码数</el-col>
							<el-col :span="3">活码重量</el-col>
							<el-col :span="3">总件数</el-col>
							<el-col :span="3">入库总重量</el-col>
						</el-row>
					</template>
					<template slot-scope="scope">
						<div class="machine-box-inner">
							<div
								v-for="(item, index) in scope.row.positionList"
								:key="item.id"
								class="machine-box-inner"
								:class="item.parentId ? 'forbid machine-container-item' : 'machine-container-item'"
							>
								<el-row :gutter="24">
									<el-col :span="6">
										<el-tag
											v-if="pageType !== 'detail'"
											closable
											@close="onRemoveMachine(item, index, scope.rowIndex)"
										>{{ item.name }}</el-tag>
										<div v-else>{{ item.name }}</div>
									</el-col>
									<el-col :span="3">
										<jk-number-input v-if="pageType !== 'detail'" v-model="item.applyInNum" size="mini"></jk-number-input>
										<div v-else>{{ item.applyInNum }}</div>
									</el-col>
									<el-col :span="3">
										<jk-number-input v-if="pageType !== 'detail'" v-model="item.applyInQty" size="mini"></jk-number-input>
										<div v-else>{{ item.applyInQty }}</div>
									</el-col>
									<el-col :span="3">
										<jk-number-input v-if="pageType !== 'detail'" v-model="item.packLiveCode" size="mini"></jk-number-input>
										<div v-else>{{ item.packLiveCode }}</div>
									</el-col>
									<el-col :span="3">
										<jk-number-input v-if="pageType !== 'detail'" v-model="item.packLiveCodeQty" size="mini"></jk-number-input>
										<div v-else>{{ item.packLiveCodeQty }}</div>
									</el-col>
									<el-col :span="3">
										<jk-number-input v-if="pageType !== 'detail'" v-model="item.inPackageQty" size="mini"></jk-number-input>
										<div v-else>{{ item.inPackageQty }}</div>
									</el-col>
									<el-col :span="3">
										<jk-number-input v-if="pageType !== 'detail'" v-model="item.inQty" size="mini"></jk-number-input>
										<div v-else>{{ item.inQty }}</div>
									</el-col>
								</el-row>
							</div>
							<div class="machine-item">
								<el-tag v-if="pageType !== 'detail'" class="el-icon-plus" style="width: 100%; cursor:pointer; text-align: center" @click="onAddMachineBtn($event, scope.rowIndex)"></el-tag>
							</div>
						</div>
					</template>
				</vxe-column>
			</jk-table>
		</el-form>
		<remote-search-product-input
			:default-select-rows="selectedEmpMachineList"
			:warehouse-id="warehouseId"
			:dialog-state="selectMachineDialogState"
			@on-confirm="onConfirmBtnOfSelectMachineDialog"
			@on-visible-change="onVisibleChangeOfSelectMachineDialog"
		>
		</remote-search-product-input>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        productionPackageApplyInStorageCreate,
        productionPackageApplyInStorageUpdate,
        productionPackageApplyInStorageGet,
        spinWarehousePage, productionPackageApplyInStorageGetData, spinPositionPage
    } from '../../../../api/production/package';
    import { formatDate } from '../../../../utils/jk/jk-tool';
    import jkCascader from '../putInWarehouseOrder/components/jk-cascader';
    import remoteSearchProductInput from './components/remote-search-product-input/radio-select-product-dialog.vue';
    import { listDept } from '../../../../api/system/dept';
    import XEUtils from 'xe-utils';
    import repairStateBar from '../packageReport/components/repair-state-bar.vue';
    import selectMachineDialog from '../../../schedule/empMachine/components/checkbox-machine-dialog.vue';
    export default {
        mixins: [calHeight],
        components: { selectMachineDialog, repairStateBar, jkCascader, remoteSearchProductInput },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                selectedEmpMachineList: [],
                selectMachineDialogState: false,
                tableLoading: false,
                saveBtnLoading: false,
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    'belongDate': '',
                    'code': '',
                    'deptCode': '',
                    'deptId': null,
                    'deptName': '',
                    'packageInStorageItemList': [],
                    'qrCode': '',
                    'remark': '',
                    'saleAddress': '',
                    'typeCode': '',
                    'typeId': 1,
                    'typeName': '',
                    'warehouseCode': '',
                    'warehouseId': null,
                    'warehouseName': '',
                    'workshopCode': '',
                    'workshopName': ''
                },
                warehouseId: null,
                positionList: [],
                positionIndex: null,
                machineList: [],
                rules: {
                    belongDate: [{ required: true, trigger: 'change' }],
                    warehouseId: [{ required: true, trigger: 'change' }],
                    typeId: [{ required: true, trigger: 'change' }]
                },
                warehouseList: [],
                typeList: [
                    { id: 1, code: 'A', name: '自制成品入库' },
                    { id: 2, code: 'B', name: '下脚料入库' }
                ],
                noCalKey: ['applyInNum', 'applyInQty', 'packLiveCodeQty', 'inPackageQty', 'inQty'],
                deptList: [],
                defaultRowData: {
                    'processId': '',
                    'processCode': '',
                    'processName': '',
                    'unitPrice': null
                }
            };
        },
        methods: {
            onRemoveMachine(item, index, rowIndex) {
                this.ruleForm.packageInStorageItemList[rowIndex].positionList.splice(index, 1);
            },
            onAddMachineBtn(item, index) {
                this.positionIndex = index;
                this.selectedEmpMachineList = this.ruleForm.packageInStorageItemList[index].positionList || [];
                this.selectMachineDialogState = true;
            },
            onConfirmBtnOfSelectMachineDialog(e) {
                if (e.length) {
                    e.forEach(x => {
                        this.ruleForm.packageInStorageItemList[this.positionIndex].positionList.push(
                            {
                                id: x.id,
                                code: x.code,
                                name: x.name,
                                applyInNum: 0,
                                applyInQty: 0,
                                packLiveCode: 0,
                                packLiveCodeQty: 0,
                                inPackageQty: 0,
                                inQty: 0
                            }
                        );
                    });
                    this.selectMachineDialogState = false;
                }
            },
            onVisibleChangeOfSelectMachineDialog(e) {
                this.selectMachineDialogState = e;
            },
            // 纸管颜色
            paperTubeList(item) {
                if (item && item.length) {
                    let trueName = '';
                    let falseName = '';
                    for (const x of item) {
                        if (x.auditState === true) {
                            trueName = x.name;
                            break; // 找到第一个 true 名字后退出循环
                        }
                    }
                    for (const x of item) {
                        if (x.auditState === false) {
                            falseName = x.name;
                            break; // 找到第一个 false 名字后退出循环
                        }
                    }
                    return trueName || falseName;
                }
                return '';
            },
            // 腰绳颜色
            waistPopeList(item) {
                if (item && item.length) {
                    let trueName = '';
                    let falseName = '';
                    for (const x of item) {
                        if (x.auditState === true) {
                            trueName = x.name;
                            break; // 找到第一个 true 名字后退出循环
                        }
                    }
                    for (const x of item) {
                        if (x.auditState === false) {
                            falseName = x.name;
                            break; // 找到第一个 false 名字后退出循环
                        }
                    }
                    return trueName || falseName;
                }
                return '';
            },
            // 标签颜色
            labelColorList(item) {
                if (item && item.length) {
                    let trueName = '';
                    let falseName = '';
                    for (const x of item) {
                        if (x.auditState === true) {
                            trueName = x.name;
                            break; // 找到第一个 true 名字后退出循环
                        }
                    }
                    for (const x of item) {
                        if (x.auditState === false) {
                            falseName = x.name;
                            break; // 找到第一个 false 名字后退出循环
                        }
                    }
                    return trueName || falseName;
                }
                return '';
            },
            onSelectBatchChange(e, index) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm.packageInStorageItemList[index], 'positionName', e.name);
                    this.$set(this.ruleForm.packageInStorageItemList[index], 'positionCode', e.code);
                    this.$set(this.ruleForm.packageInStorageItemList[index], 'positionId', e.id);
                }
            },
            onWarehouseChange(val) {
                this.warehouseList.forEach((x) => {
                    if (x.id === val) {
                        this.$set(this.ruleForm, 'warehouseCode', x.code);
                        this.$set(this.ruleForm, 'warehouseId', x.id);
                        this.$set(this.ruleForm, 'warehouseName', x.name);
                        this.warehouseId = x.id;
                    }
                });
                this.ruleForm.packageInStorageItemList.forEach(x => {
                    x.positionList = [];
                });
            },
            onDeptChange(id, e) {
                this.$set(this.ruleForm, 'deptId', e.id);
                this.$set(this.ruleForm, 'deptCode', e.code);
                this.$set(this.ruleForm, 'deptName', e.name);
            },
            footerMethod({ columns, data }) {
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return '合计';
                        }
                        if (this.noCalKey.includes(column.property)) {
                            return XEUtils.sum(data, column.property);
                        }
                        return null;
                    })
                ];
            },
            getOrderInfoRequest() {
                this.$set(this.ruleForm, 'packageInStorageItemList', []);
                if (!this.ruleForm.belongDate) return;
                return productionPackageApplyInStorageGetData({
                    belongDate: this.ruleForm.belongDate
                }).then(res => {
                    if (res.data.status === 200) {
                        this.$set(this.ruleForm, 'packageInStorageItemList', res.data.res || []);
                    }
                });
            },
            onDeleteBtn(scope) {
                this.ruleForm.packageInStorageItemList.splice(scope.rowIndex, 1);
            },
            onAddBtn() {
                this.ruleForm.packageInStorageItemList.push(JSON.parse(JSON.stringify(this.defaultRowData)));
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));

                const warehouseItem = this.warehouseList.find(x => x.id === params.warehouseId) || {};
                params.warehouseCode = warehouseItem.code;
                params.warehouseName = warehouseItem.name;

                const typeItem = this.typeList.find(x => x.id === params.typeId) || {};
                params.typeCode = typeItem.code;
                params.typeName = typeItem.name;

                if (!this.dataId) {
                    params.auditState = 1;
                    delete params.id;
                }
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                const api = !this.dataId ? productionPackageApplyInStorageCreate : productionPackageApplyInStorageUpdate;
                this.saveBtnLoading = true;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return productionPackageApplyInStorageGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.packageInStorageItemList = resData.packageInStorageItemList || [];
                        this.ruleForm = res.data.res;
                        this.warehouseId = this.ruleForm.warehouseId;
                        // this.getPositionRequest(this.ruleForm.warehouseId);
                    }
                });
            },
            getWarehouseListRequest() {
                return spinWarehousePage().then(res => {
                    if (res.data.status === 200) {
                        this.warehouseList = res.data.res || {};
                        if (!this.ruleForm.warehouseName) {
                            this.$set(this.ruleForm, 'warehouseCode', this.warehouseList[3].code);
                            this.$set(this.ruleForm, 'warehouseId', this.warehouseList[3].id);
                            this.$set(this.ruleForm, 'warehouseName', this.warehouseList[3].name);
                            this.warehouseId = this.warehouseList[3].id;
                        }
                    }
                });
            },
            getDeptListRequest() {
                return listDept({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.deptList = res.data.res || {};
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                }
                await this.getOrderInfoRequest();
                await this.getDeptListRequest();
                await this.getWarehouseListRequest();
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
